import { SuperMap3D } from '@/utils/supermap3d';
import { AnalysisContext, BaseAnalysis } from '@/utils/analysis/BaseAnalysis';

export class ProfileAnalysis extends BaseAnalysis {
  private handlerLine: any;
  private profile: any;

  constructor(ctx: AnalysisContext) {
    super(ctx);
    this.profile = new SuperMap3D.Profile(this.viewer.scene);
    this.handlerLine = new SuperMap3D.DrawHandler(this.viewer, SuperMap3D.DrawMode.Line);
    this.initEvents();
  }

  private initEvents() {
    this.handlerLine.activeEvt.addEventListener((isActive: boolean) => {
      if (isActive) {
        this.viewer.enableCursorStyle = false;
        document.body.classList.add('drawCur');
      } else {
        this.viewer.enableCursorStyle = true;
        document.body.classList.remove('drawCur');
      }
    });

    //SuperMap3D.Cartesian2
    this.handlerLine.movingEvt.addEventListener((pos: any) => {
      this.tooltip?.showAt(pos, this.handlerLine.isDrawing ? '点击绘制第二个点，右键结束' : '点击绘制第一个点');
    });

    this.handlerLine.drawEvt.addEventListener((result: any) => {
      this.tooltip?.setVisible(false);

      const [start, end] = result.object.positions;
      this.handlerLine.clear();

      const startCarto = SuperMap3D.Cartographic.fromCartesian(start);
      const endCarto = SuperMap3D.Cartographic.fromCartesian(end);

      this.profile.startPoint = [SuperMap3D.Math.toDegrees(startCarto.longitude), SuperMap3D.Math.toDegrees(startCarto.latitude), startCarto.height];

      this.profile.endPoint = [SuperMap3D.Math.toDegrees(endCarto.longitude), SuperMap3D.Math.toDegrees(endCarto.latitude), endCarto.height];

      this.profile.extendHeight = 40;

      this.profile.getBuffer((buffer: Uint8ClampedArray) => {
        const canvas = document.getElementById('canvas-container') as HTMLCanvasElement;
        if (canvas) {
          canvas.width = this.profile._textureWidth;
          canvas.height = this.profile._textureHeight;
          const ctx = canvas.getContext('2d');
          if (ctx) {
            const imgData = ctx.createImageData(canvas.width, canvas.height);
            imgData.data.set(buffer);
            ctx.putImageData(imgData, 0, 0);
            canvas.style.width = '800px';
            canvas.style.height = '450px';
          }
        }
      });

      this.profile.build();
    });
  }

  public activate(): void {
    this.clear();
    this.handlerLine.activate();
  }

  public clear(): void {
    this.handlerLine.clear();
    const canvas = document.getElementById('canvas-container') as HTMLCanvasElement;
    if (canvas) {
      canvas.style.width = '0px';
      canvas.style.height = '0px';
    }
  }
}
